/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ui;

import controller.ClienteDAO;
import controller.ProjetoDAO;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import models.Cliente;
import models.Projeto;
import utils.enums.projeto.SituacaoProjeto;
import utils.enums.projeto.StatusProjeto;
import utils.nucleo.Nucleo;
import utils.observer.Observer;

/**
 *
 * @author Oliver Kraemer
 */
public class CadProjeto extends javax.swing.JPanel {

    private class CadProjetoObserver implements Observer {
        @Override
        public void update() {
            loadClientes();
        }
    };
    
    Projeto projeto;

    /**
     * Creates new form CadProjeto
     */
    public CadProjeto() {
        this(true);
    }
    
    public CadProjeto(Projeto projeto) {
        this(false);
        this.projeto = projeto;
        this.loadProjeto();
    }

    private CadProjeto(boolean inclusao) {
        initComponents();
        
        if (inclusao) {
            this.projeto = new Projeto();
            this.loadProjeto();
        }
        
        ClienteDAO.getInstance().getSubject().registerObserver(new CadProjetoObserver());
    }
    
    private void loadProjeto() {
        jTFNome.setText(this.projeto.getNome());
        jTADescricao.setText(this.projeto.getDescricao());

        SimpleDateFormat out = new SimpleDateFormat("dd/MM/yyyy");

        jFTFDataInicio.setText(out.format(this.projeto.getDataInicio()));
        jFTFDataEntrega.setText(out.format(this.projeto.getDataEntrega()));

        this.loadSituacoes();
        this.loadStatus();
        this.loadClientes();
    }

    private void loadSituacoes() {
        DefaultListModel<SituacaoProjeto> lista = new DefaultListModel<>();
        int selectedIndex = 0;

        for( SituacaoProjeto sp : SituacaoProjeto.values() ) {
            lista.addElement(sp);
            
            if ( sp.equals(projeto.getSituacao()) ) {
                selectedIndex = lista.size()-1;
            }
        }

        jLSituacoes.setModel(lista);
        jLSituacoes.setSelectedIndex(selectedIndex);
    }
    
    private void loadStatus() {
        DefaultListModel<StatusProjeto> lista = new DefaultListModel<>();
        int selectedIndex = 0;
        
        for( StatusProjeto sp : StatusProjeto.values() ) {
            lista.addElement(sp);

            if ( sp.equals(projeto.getStatus()) ) {
                selectedIndex = lista.size()-1;
            }
        }
        
        jLStatus.setModel(lista);
        jLStatus.setSelectedIndex(selectedIndex);
    }
    
    private void loadClientes() {
        jCBCliente.removeAllItems();
        for (Cliente cliente : ClienteDAO.getClientes()) {
            jCBCliente.addItem(cliente);
            
            if ( cliente.equals(this.projeto.getCliente()) ) {
                jCBCliente.setSelectedIndex(jCBCliente.getItemCount()-1);
            }
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTFNome = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTADescricao = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jLSituacoes = new javax.swing.JList();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jLStatus = new javax.swing.JList();
        jLabel6 = new javax.swing.JLabel();
        jFTFDataInicio = new javax.swing.JFormattedTextField();
        jFTFDataEntrega = new javax.swing.JFormattedTextField();
        jLabel7 = new javax.swing.JLabel();
        jCBCliente = new javax.swing.JComboBox();

        jTADescricao.setColumns(20);
        jTADescricao.setRows(5);
        jScrollPane1.setViewportView(jTADescricao);

        jLabel1.setText("Nome:");

        jLabel2.setText("Descrição:");

        jButton1.setText("Salvar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel3.setText("Data de Início:");

        jLabel4.setText("Data de Entrega:");

        jLSituacoes.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane2.setViewportView(jLSituacoes);

        jLabel5.setText("Situação:");

        jLStatus.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane3.setViewportView(jLStatus);

        jLabel6.setText("Status:");

        jFTFDataInicio.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter()));
        jFTFDataInicio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFTFDataInicioActionPerformed(evt);
            }
        });

        jFTFDataEntrega.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter()));

        jLabel7.setText("Cliente:");

        jCBCliente.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel7)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5)
                            .addComponent(jLabel6))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 314, Short.MAX_VALUE)
                            .addComponent(jCBCliente, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jFTFDataInicio, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jTFNome, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jFTFDataEntrega, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(0, 0, Short.MAX_VALUE))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTFNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(49, 49, 49)
                        .addComponent(jLabel2)))
                .addGap(9, 9, 9)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(jCBCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jFTFDataInicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jFTFDataEntrega, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(27, 27, 27)
                        .addComponent(jLabel5))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(14, 14, 14)
                        .addComponent(jLabel6)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 54, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        projeto.setNome(jTFNome.getText());
        projeto.setDescricao(jTADescricao.getText());

        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");

        try {
            if ( jFTFDataEntrega.getText().isEmpty() ) {
                this.projeto.setDataEntrega(null);
            } else {
                this.projeto.setDataEntrega(new Date(format.parse(jFTFDataEntrega.getText()).getTime()));
            }
        } catch (ParseException ex) {
            JOptionPane.showMessageDialog(null, "Data de Entrega inválida.");
            return;
        }

        try {
            if ( jFTFDataInicio.getText().isEmpty() ) {
                this.projeto.setDataInicio(null);
            } else {
                this.projeto.setDataInicio(new Date(format.parse(jFTFDataInicio.getText()).getTime()));
            }
        } catch (ParseException ex) {
            JOptionPane.showMessageDialog(null, "Data de Início inválida.");
            return;
        }
        
        this.projeto.setSituacao((SituacaoProjeto) jLSituacoes.getSelectedValue());
        this.projeto.setStatus((StatusProjeto) jLStatus.getSelectedValue());
        this.projeto.setCliente((Cliente) jCBCliente.getSelectedItem());
        
        if ( this.projeto.getId() == 0 ) {
            ProjetoDAO.inserir(projeto);
        } else {
            ProjetoDAO.alterar(projeto);
        }

        Nucleo.getInstance().getPrincipal().fecharTela(this);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jFTFDataInicioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFTFDataInicioActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jFTFDataInicioActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jCBCliente;
    private javax.swing.JFormattedTextField jFTFDataEntrega;
    private javax.swing.JFormattedTextField jFTFDataInicio;
    private javax.swing.JList jLSituacoes;
    private javax.swing.JList jLStatus;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextArea jTADescricao;
    private javax.swing.JTextField jTFNome;
    // End of variables declaration//GEN-END:variables
}
